package com.eco.fanliapp.admin.controller.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.admin.annotation.SysLogAnnotation;
import com.eco.fanliapp.admin.common.BaseController;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.Convert;
import com.eco.fanliapp.utils.StringUtils;
import com.eco.fanliapp.vo.AppGoodsRequestParams;
import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 商品（appGoods）controller
 */
@RestController
@RequestMapping("/web/appGoods")
public class AppGoodsController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(AppGoodsController.class);

    @Autowired
    private IAppGoodsService iAppGoodsService;
    @Autowired
    private IAppGoodsClassifyService appGoodsClassifyService;

    @Autowired
    ISubAccountService subUserService;

    @Autowired
    private ITaoBaoService taoBaoService;

    @Autowired
    private IAppGoodsCoolqService appGoodsCoolqService;
    @Autowired
    private ISyLabelTypeService iSyLabelTypeService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;

    // key过期时间（秒）
    private final Long EXPIRETIME = 60L;

    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ServerResponse appGoodsList(@RequestBody AppGoodsRequestParams appGoodsParams) {
        //分页
        if (appGoodsParams.getPageNum() == null) appGoodsParams.setPageNum(1);
        if (appGoodsParams.getPageSize() == null) appGoodsParams.setPageSize(20);
        Page<AppGoods> page = new Page<>(appGoodsParams.getPageNum(), appGoodsParams.getPageSize());
//        //查询条件
        QueryWrapper<AppGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
//        //用户类型
//        queryWrapper.ne("add_user_id", appGoodsParams.getAddUserId());
        //发布时间区间查询
        condition(appGoodsParams.getStartCreateTime(), appGoodsParams.getEndCreateTime(), queryWrapper, "create_time");

        //店铺类型
        if (StringUtils.isNotNull(appGoodsParams.getShoptype()))
            queryWrapper.eq("shoptype", appGoodsParams.getShoptype());
        //分类
        if (StringUtils.isNotNull(appGoodsParams.getFqcat()))
            queryWrapper.eq("fqcat", appGoodsParams.getFqcat());
        //商品类型

        //价格区间
        condition(appGoodsParams.getMinItemprice(), appGoodsParams.getMaxItemprice(), queryWrapper, "itemprice");
        //销量区间
        condition(appGoodsParams.getMinItemsale(), appGoodsParams.getMaxItemsale(), queryWrapper, "itemprice");
        //关键字
        if (StringUtils.isNotNull(appGoodsParams.getItemtitle()))
            queryWrapper.like("itemshorttitle", appGoodsParams.getItemtitle());
//        //商品名字
//        if (StringUtils.isNotNull(appGoodsParams.getItemtitle()))
//            queryWrapper.eq("itemtitle", appGoodsParams.getItemtitle());
        //商品id

        if (StringUtils.isNotNull(appGoodsParams.getItemid())) {

            queryWrapper.eq("itemid", appGoodsParams.getItemid());
        }
        String column = appGoodsParams.getColumn();
        if (StringUtils.isNotNull(column) && StringUtils.isNotNull(appGoodsParams.getDescOrAsc())) {
            column = column.replace("createTime", "create_Time");
            column = column.replace("topSerialNumber", "top_serial_number");
            if ("1".equals(appGoodsParams.getDescOrAsc())) queryWrapper.orderByDesc(column);
            else queryWrapper.orderByAsc(column);
        }
        if (StringUtils.isNotNull(appGoodsParams.getRecommend())) {
            if ("1".equals(appGoodsParams.getRecommend())) {
                queryWrapper.eq("recommend", appGoodsParams.getRecommend());
                queryWrapper.orderByAsc("sort");
            }
        }
        IPage<AppGoods> appGoodsIPage = iAppGoodsService.page(page, queryWrapper);
        List<AppGoods> appGoodsList = new ArrayList<>();
        if (appGoodsIPage != null && appGoodsIPage.getRecords() != null) {
            //查询商品分类数据
            List<AppGoodsClassify> appGoodsClassifies = appGoodsClassifyService.selectAppGoodsClassifyList(new AppGoodsClassify());

            for (AppGoods appGoods : appGoodsIPage.getRecords()) {
                appGoods.setFixedSort(-1);
                String fixedSort_key = "app_fixedSortGoods_list";
                if (redisTemplateService.hasKey(fixedSort_key)) {
                    Map<String, Integer> map = redisTemplateService.getMap(fixedSort_key, Map.class);
                    for (String key : map.keySet()) {
                        if (key.equals(appGoods.getItemid())) {
                            if (map.get(key) != -1) {
                                appGoods.setFixedSort(map.get(key));
                            }
                        }
                    }
                }
                List<SyLabelType> syLabelType = iSyLabelTypeService.selectLabelName(appGoods.getItemid());
                if (syLabelType != null) {
                    appGoods.setLabelTypeList(syLabelType);
                }
                if (appGoods.getAddUserId() == -1) {
                    appGoods.setAddUserName("QQ群添加");
                } else {
                    SubAccount subAccount = subUserService.selectSubAccountById(appGoods.getAddUserId());
                    if (subAccount != null) appGoods.setAddUserName(subAccount.getNickName());
                }
                appGoodsList.add(appGoods);
                //设置商品分类
                for (AppGoodsClassify appGoodsClassify : appGoodsClassifies) {
                    if (appGoods.getFqcat() != null && org.apache.commons.lang3.StringUtils.isNumeric(appGoods.getFqcat()) && Integer.valueOf(appGoods.getFqcat()) == appGoodsClassify.getCid()) {
                        appGoods.setFqcat(appGoodsClassify.getCname());
                        break;
                    }
                }
                //计算佣金
                String itemprice = appGoods.getItemprice();
                String tkrates = appGoods.getTkrates();
                if (StringUtils.isNotNull(itemprice) && StringUtils.isNotNull(tkrates)) {
                    BigDecimal itempriceBg = new BigDecimal(itemprice);
                    BigDecimal tkratesBg = new BigDecimal(tkrates);
                    appGoods.setCommission(itempriceBg.multiply(tkratesBg).divide(new BigDecimal("100")));
                }

            }
        }
        appGoodsIPage.setRecords(appGoodsList);
        return ServerResponse.createBySuccess("数据获取成功", appGoodsIPage);
    }

    /**
     * 更新商品信息（单个）
     *
     * @param appGoods
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ServerResponse updateAppGoods(@RequestBody AppGoods appGoods) {
        int i = iAppGoodsService.updateAppGoods(appGoods);
        if (i == 2) {
            return ServerResponse.createByErrorMessage("排序序号已存在");
        }
        if (i > 0) {
//            try {
//                String goods = JSONObject.toJSONString(appGoods);
//                HttpClient httpclient = HttpClients.createDefault();
//                String url = ApiEnum.EUREKA_URL + "/eureke/lucene/updateIndex";
//                HttpPost httpPost = new HttpPost(url);
//                httpPost.setEntity(new StringEntity(goods, "UTF-8"));
//                httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
//                httpPost.setHeader("Accept", "application/json");
//                HttpResponse httpResponse = httpclient.execute(httpPost);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            return ServerResponse.createBySuccessMessage("商品更新成功");
        }
        return ServerResponse.createByErrorMessage("商品更新失败");
    }

    /**
     * 更新商品置顶同时添加置顶商品
     *
     * @return
     */
    @RequestMapping(value = "updateTop", method = RequestMethod.POST)
    public ServerResponse updateTopAppGoods(@RequestBody Map map) {
        return iAppGoodsService.updateTopAppGoods(map);
    }


    /**
     * 删除商品 可以多个 以逗号隔开
     *
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @SysLogAnnotation(value = "删除商品", userType = 2)
    public ServerResponse deleteAppGoods(@RequestBody Map ids) {
        String[] tableId = Convert.toStrArray(MapUtils.getString(ids, "ids"));
        StringBuilder itemids = new StringBuilder();
        for (int y = 0; y < tableId.length; y++) {
            AppGoods appGoods = iAppGoodsService.selectAppGoodsById(Long.valueOf(tableId[y]));
            itemids.append(appGoods.getItemid() + ",");
        }

        int i = iAppGoodsService.updateAppGoodsByIds(MapUtils.getString(ids, "ids"));

        if (i > 0) {
            List<AppGoods> appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
            taoBaoService.getRedisRecommendGoodsList(appGoodsList);
//            iAppGoodsService.deleteIndex(itemids.toString(), "delete");
        }
        if (i <= 0) return ServerResponse.createByErrorMessage("商品删除失败");
        return ServerResponse.createBySuccess("商品删除成功", ids);
    }


    private void condition(String min, String max, QueryWrapper queryWrapper, String column) {
        if (StringUtils.isNotNull(min) && StringUtils.isNotNull(max)) {
            queryWrapper.le(column, max);
        } else if (StringUtils.isNotNull(min) && StringUtils.isNotNull(max)) {
            queryWrapper.ge(column, min);
        } else if (StringUtils.isNotNull(min) && StringUtils.isNotNull(max)) {
            queryWrapper.between(column, min, max);
        }
    }


    // 获取首页类目
    @GetMapping("/getClassify")
    @ResponseBody
    public ServerResponse<List<AppGoodsClassify>> getClassify() {
        return taoBaoService.getClassify();
    }

    @SysLogAnnotation(value = "商品添加", userType = 2)
    @RequestMapping(value = "add")
    public ServerResponse addAppGoods(@RequestBody AppGoods appGoods, Boolean isQqadd) {
        Integer userId = 0;

        if (isQqadd != null && isQqadd) {
            userId = -1;
        } else {
            if (getAuthentication().getRoleId() != 0) {
                userId = getAuthentication().getUserId();
            }
        }
        ServerResponse response = iAppGoodsService.addAppGoods(appGoods, userId);
        if (response.getStatus() == 200) {
            List<AppGoods> appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
            taoBaoService.getRedisRecommendGoodsList(appGoodsList);
        }
        return response;
    }

    public static void main(String args[]) {
//        CoolqData data = new CoolqData();
//        data.setGroup(135932737L);
//        data.setMsg("ceshi 成功");
//        data.setFun("sendGroupMsg");
        String aa = "-11230a";
        String reg = "\\-.+?-";

//        a.sendSocketData("http://localhost:8099", data.toJson());
    }


}
